<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 游戏账号信息生成信息图片并上传
 */
class GdCreateImage extends Api
{
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];
	public function ceshi(){
		$goods_id = 1822;
		$goods_info = Db::name('goods')->where('id','=',$goods_id)->field('sku,info')->find();
		$this->index($goods_info['sku'],$goods_info['info']);
	}

	//游戏账号信息生成信息图片并上传
	public function index($sku, $info)
	{
		//        $goods_info = Db::name('goods')->where('id','=',$goods_id)->field('sku,info')->find();
		if (!$sku) {
			return json_encode(['code' => 0, 'msg' => '参数错误']);
		}
		// 引入系统字库
		// putenv('GDFONTPATH=c:\WINDOWS\Fonts');
		putenv('GDFONTPATH=/www/wwwroot/test/public/fonts');
		//商品基本信息
		if ($sku) {
			$basestr = htmlspecialchars_decode($sku);
			$base_arr = json_decode($basestr, true);
		} else {
			return json_encode(['code' => 0, 'msg' => '该商品无基本信息']);
		}
		//账号信息
		if ($info) {
			$accountstr = htmlspecialchars_decode($info);
			$account_arr = json_decode($accountstr, true);
		}

		// foreach($account_arr as $k => $v){
		//     $v = implode(",",$v);
		//     $v = substr($v,1);
		//     dump($v);
		// }
		// dump($account_arr);exit;
		//判断info字数引入不同大小的背景图
		$newStr = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $accountstr);  //正则匹配中文
		$infonum = mb_strlen($newStr, 'utf-8');
		//行数
		$inforow = ceil($infonum/28);
		//图一次加两行
		$height = ($inforow % 2) == 0 ? $inforow : $inforow+1;
		if($height < 6){
			$height = 6;
		}
		//背景图
		$imgs = 'uploads/bggameinfoimg/bg'.$height.'.jpg'; //目标大图，背景图的链接
		$size = 18; //字体大小（9磅=14px）
		// $font = 'simhei.ttf';
		$font = 'SIMHEI.TTF';
		$img = imagecreatefromjpeg($imgs); // 加载已有图像
		$white = imagecolorallocate($img, 255, 255, 255); //设置字体颜色
		$yellow = imagecolorallocate($img, 237, 213, 81); //设置字体颜色

		//基础信息
		$base_x = 140; //首个字的横坐标
		$base_y = 130; //首个字的纵坐标

		$base_i = 0;

		foreach ($base_arr as $k => $v) {
			imagettftext($img, $size, 0, $base_x, $base_y, $white, $font, $k . ":"); //循环添加文字
			imagettftext($img, $size, 0, $base_x + 1, $base_y, $white, $font, $k . ":"); //字体加粗
			$key_x = $base_x + mb_strlen($k, 'UTF8') * 28 + 6;
			imagettftext($img, $size, 0, $key_x, $base_y, $yellow, $font, $v); //循环添加文字值
			imagettftext($img, $size, 0, $key_x + 1, $base_y, $yellow, $font, $v); //字体加粗
			$base_i++;
			if ($base_i >= 3) {
				$base_i = 0; //重置换行，一行展示3个属性
				$base_y = $base_y + 40; //增加纵坐标来做到间距的效果
				$base_x = 140;
			} else {
				$base_x = $base_x + 315; //增加横坐标来做到间距的效果
			}
		}
		//账号信息
		$account_x = 100; //首个字的横坐标
		$account_y = 380; //首个字的纵坐标
		if ($account_arr) {
			foreach ($account_arr as $k => $v) {
				//定义一个空字串
				$str = '';
				//属性值个数
				// $num = count($value);
				// $k = $k."(".$num."个):";
				imagettftext($img, $size, 0, $account_x, $account_y, $white, $font, $k . ":"); //循环添加文字
				imagettftext($img, $size, 0, $account_x + 1, $account_y, $white, $font, $k . ":"); //字体加粗
				$key_x = $account_x + mb_strlen($k, 'UTF8') * 28 + 6;
				$v = implode(",", $v);
				$v = substr($v, 1);
				$str = $k . ":" . $v;
				$str_len = mb_strlen($str, 'UTF8');
				if ($str_len > 36) {
					//根据字符串长度切割成数组
					$v_arr = $this->mbStrSplit($v, 37);
					$v_arr_count = count($v_arr);
					foreach ($v_arr as $v_k => $vv) {
						// if($v_k == 0){
						imagettftext($img, $size, 0, $account_x + mb_strlen($k, 'UTF8') * 28 + 6, $account_y, $yellow, $font, $vv); //循环添加文字值
						imagettftext($img, $size, 0, $account_x + mb_strlen($k, 'UTF8') * 28 + 7, $account_y, $yellow, $font, $vv); //字体加粗
						// }else{
						//     imagettftext($img, $size, 0, $account_x, $account_y, $yellow, $font, $vv);//循环添加文字值
						// }
						if ($v_k < $v_arr_count - 1) {
							$account_x = 100;   //重置x轴
							$account_y = $account_y + 38; //增加纵坐标来做到间距的效果（小间距）
						}
					}
				} else {
					imagettftext($img, $size, 0, $account_x + mb_strlen($k, 'UTF8') * 28 + 6, $account_y, $yellow, $font, $v); //循环添加文字值
					imagettftext($img, $size, 0, $account_x + mb_strlen($k, 'UTF8') * 28 + 7, $account_y, $yellow, $font, $v); //字体加粗
				}
				$account_x = 100;   //重置x轴
				$account_y = $account_y + 42; //增加纵坐标来做到间距的效果（大间距）

			}
		}

		$picname = rand(1, 10000) . time() . ".jpeg"; //定义图片名
		$dir = 'uploads' . "/" . date('Ymd', time());
		if (!file_exists($dir)) {
			mkdir($dir, 0777, true);
		}
		$picurl = $dir . '/' . $picname;
		ImageJPEG($img, $picurl); //保存图片
		//把图片上传到oss
		try {
			$config = [
				'accessId'      => 'LTAI5tAn6aMvP2adPLsDa8eJ',
				'accessKey'     => '9HSoGgjlHukLtELYYvjewmOVe3H2f1',
				'bucket'        => '780g',
				'endpoint'      => 'https://oss-cn-zhangjiakou.aliyuncs.com',
				'host'          => 'https://780g.oss-cn-zhangjiakou.aliyuncs.com',
			];
			$ossClient = new OssClient($config['accessId'], $config['accessKey'], $config['endpoint']);
			$result = $ossClient->uploadFile($config['bucket'], $picurl, $picurl);
			$url = $result['info']['url'];
			$img = explode('com', $url);
			$img = $img[1];
			// echo $img;
			return json_encode(['code' => 0, 'msg' => '成功', 'url' => $picurl]);
		} catch (OssException $e) {
			// 失败记录错误查日志
			return json_encode(['code' => 0, 'msg' => $e->getMessage()]);
		}
		return json_encode(['code' => 0, 'msg' => '成功', 'url' => $picurl]);
	}


	public function mbStrSplit($string, $len = 1)
	{
		$start = 0;
		$strlen = mb_strlen($string);
		while ($strlen) {
			$array[] = mb_substr($string, $start, $len, "utf8");
			$string = mb_substr($string, $len, $strlen, "utf8");
			$strlen = mb_strlen($string);
		}
		return $array;
	}
}
